package base.http.rxandroid

import base.sys.LauncherApplication
import rx.Observable
import rx.Scheduler
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action0
import rx.functions.Func1
import rx.schedulers.Schedulers

/**
 * Created by Administrator on 2018/4/28.
 */
class RxUtils<T> {
    fun <T> createDialogObservable(observable: Observable<T>, dialog: Action0): Observable<T> {
        return Observable.just(LauncherApplication().isActivityVisible())
                .doOnSubscribe(dialog)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(Func1<Boolean, Observable<T>> { aBoolean ->
                    if (aBoolean!!) {
                        observable
                    } else {
                        null
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
    }

    fun <T> createDialogObservable(observable: Observable<T>, dialog: Action0, mainThread: Scheduler): Observable<T> {
        return Observable.just(LauncherApplication().isActivityVisible())
                .doOnSubscribe(dialog)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(Func1<Boolean, Observable<T>> { aBoolean ->
                    if (aBoolean!!) {
                        observable
                    } else {
                        null
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(mainThread)
    }

    fun <T> createObservable(observable: Observable<T>): Observable<T>? {
        return Observable.just(LauncherApplication().isActivityVisible())
                .flatMap(Func1<Boolean, Observable<T>> { aBoolean ->
                    if (aBoolean!!) {
                        observable
                    } else {
                        null
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
    }

    fun <T> createObservable(observable: Observable<T>, mainThread: Scheduler): Observable<T> {
        return Observable.just(LauncherApplication().isActivityVisible())
                .flatMap(Func1<Boolean, Observable<T>> { aBoolean ->
                    if (aBoolean!!) {
                        observable
                    } else {
                        null
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(mainThread)
    }
}